package com.sc.web.gwt.server.security;

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class DataEncryptor {
    private KeyGenerator keyGenerator;
    private SecretKey secretKey;
    private Cipher desCipher;

    public DataEncryptor() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
        keyGenerator = KeyGenerator.getInstance("DES");
        secretKey = keyGenerator.generateKey();
        desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    }

    public String encryptData(String data) {
        byte[] dataAfterEncrypted = null;
        try {
            desCipher.init(Cipher.ENCRYPT_MODE, secretKey);
            dataAfterEncrypted = desCipher.doFinal(data.getBytes());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return new String(dataAfterEncrypted);
    }

    public String decryptData(String data) {
        byte[] dataAfterEncrypted = null;
        try {
            desCipher.init(Cipher.DECRYPT_MODE, secretKey);
            dataAfterEncrypted = desCipher.doFinal(data.getBytes());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return new String(dataAfterEncrypted);
    }

    public static void main(String args[]) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
        DataEncryptor dataEncryptor = new DataEncryptor();
        String data = dataEncryptor.encryptData("123456");
        System.out.println(data);
    }
}
